package com.stone.card;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

/**
 * 重写getChildDrawingOrder使CardSlidePanel最后一个绘制,移动的时候能改覆盖在其他view上面
 * Created by admin on 2017/7/21.
 */

public class SlidePanelWrapRelativeLayout extends RelativeLayout {
    private int targetIndex;

    private int slidePanelId;

    public SlidePanelWrapRelativeLayout(Context context) {
        this(context, null);
    }

    public SlidePanelWrapRelativeLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidePanelWrapRelativeLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public SlidePanelWrapRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidePanelWrapLinearLayout, defStyle, 0);
        slidePanelId = a.getResourceId(R.styleable.SlidePanelWrapLinearLayout_slidePanelId, -1);
        a.recycle();
        //
        setChildrenDrawingOrderEnabled(true);
        setClipChildren(false);
        setClipToPadding(false);
    }


    //    //默认是按加入到ViewGroup的顺序绘制
//    @Override
//    protected int getChildDrawingOrder(int childCount, int i) {
//        //思路：找到目标CardSlidePanel, 将其顺序和最后一个绘制的顺序交换
//        View child = getChildAt(i);
//        if (child instanceof CardSlidePanel) {//目标view最后一个绘制
//            targetIndex = i;
//            return childCount - 1;//最后一个绘制
//        } else if (i == childCount - 1) {//原本最后一个绘制的则顺序成了targetIndex
//            return targetIndex;
//        } else {
//            return i;
//        }
//    }
    //默认是按加入到ViewGroup的顺序绘制
    @Override
    protected int getChildDrawingOrder(int childCount, int i) {
        //思路：找到目标CardSlidePanel, 将其顺序和最后一个绘制的顺序交换
        View child = findViewById(slidePanelId);
        int index = indexOfChild(child);
        if (index == -1) {
            return i;
        }
        if (index == i) {//目标view最后一个绘制
            targetIndex = i;
            return childCount - 1;//最后一个绘制
        } else if (i == childCount - 1) {//原本最后一个绘制的则顺序成了targetIndex
            return targetIndex;
        } else {
            return i;
        }
    }
}